<template>
	<view class="form">
		<view class="order-container">
			<u--form labelPosition="left" :model="userInfoModel" ref="userForm" labelWidth="80">

				<u-form-item prop="userPhoto" label="头像">

					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="1" :previewFullImage="true"></u-upload>
				</u-form-item>

				<u-form-item prop="userName" label="姓名" borderBottom>
					<u--input v-model="userInfoModel.userName" placeholder="请填写您的真实姓名" border="none"
						disabledColor="#ffffff"></u--input>
				</u-form-item>


				<u-form-item label="性别" prop="userGenderText" borderBottom @click="showSex = true; hideKeyboard()">
					<u--input v-model="userInfoModel.userGenderText" disabled disabledColor="#ffffff"
						placeholder="请选择性别" inputAlign="left" border="none"></u--input>
					<u-icon slot="right" name="arrow-right" class="arrow"></u-icon>
				</u-form-item>

				<u-form-item label="收货地址" borderBottom prop="userAddress">
					<u--input v-model="userInfoModel.userAddress" placeholder="请填写您的地址信息" border="none"></u--input>
				</u-form-item>

				<u-form-item label="所在学院" borderBottom prop="userCollege">
					<u--input v-model="userInfoModel.userCollege" placeholder="请填写您的学院名称" border="none"></u--input>
				</u-form-item>


				<u-form-item label="入学年份" prop="userEnterYear" borderBottom
					@click="showEnterYear = true; hideKeyboard()">
					<u--input v-model="userInfoModel.userEnterYear" disabled disabledColor="#ffffff" inputAlign="left"
						placeholder="请选择入学年份" border="none"></u--input>
					<u-icon slot="right" name="arrow-right" class="arrow"></u-icon>
				</u-form-item>
				<u-form-item labelPosition="top" prop="userStudentCard" label="上传学生证照片" labelWidth="110" class="card"
					borderBottom>
					<u-upload :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2" multiple
						:maxCount="1" width="300" height="150" :previewFullImage="true">
						<image src="../../static/img/studentCard.png" class="student-card"></image>
					</u-upload>
				</u-form-item>

			</u--form>
			<u-action-sheet :show="showSex" :actions="sexActions" title="请选择您的性别" @close="showSex = false"
				@select="sexSelect">
			</u-action-sheet>
			<u-datetime-picker :show="showEnterYear" :value="enterYear" mode="year-month" closeOnClickOverlay
				:maxDate="enterYear" @confirm="requireTimeConfirm" @cancel="requireTimeClose"></u-datetime-picker>

		</view>

		<view class="bottom">
			<u-line color="rgb(229, 230, 235)"></u-line>
			<view class="operation">

				<view class="button">
					<u-button text="确认提交" shape="circle" @click="submit"
						color="linear-gradient(135.00deg, rgba(118,118,238,1.00) 0.321%,rgba(138,138,238,1.00) 100%)">
					</u-button>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	import {
		baseUrl
	} from '../../utils/baseConfig.js'
	export default {
		components: {},
		data() {
			return {
				userInfo: this.$store.getters?.userInfo?.userInfoDetail || null,
				fileList1: this.$store.getters?.userInfo?.userInfoDetail?.userPhoto ? [{
					url: this.$store.getters?.userInfo?.userInfoDetail?.userPhoto,
				}] : [],
				fileList2: this.$store.getters?.userInfo?.userInfoDetail?.userStudentCard ? [{
					url: this.$store.getters?.userInfo?.userInfoDetail?.userStudentCard
				}] : [],
				showSex: false,
				sexActions: [{
						name: '男',
						value: 1
					},
					{
						name: '女',
						value: 0
					},

				],
				showEnterYear: false,
				enterYear: Number(new Date()),
				userInfoModel: {
					userPhoto: this.$store.getters?.userInfo?.userInfoDetail?.userPhoto || '',
					userName: this.$store.getters?.userInfo?.userInfoDetail?.userName || '',
					userGender: this.$store.getters?.userInfo?.userInfoDetail?.userGender || '',
					userPhone: this.$store.getters?.userInfo?.userPhone || '',
					userCollege: this.$store.getters?.userInfo?.userInfoDetail?.userCollege || '',
					userEnterYear: this.$store.getters?.userInfo?.userInfoDetail?.userEnterYear || '',
					userAddress: this.$store.getters?.userInfo?.userInfoDetail?.userAddress || '',
					userGenderText: (this.$store.getters?.userInfo?.userInfoDetail && String(this.$store.getters?.userInfo
						?.userInfoDetail?.userGender)) ? (this.$store
						.getters?.userInfo?.userInfoDetail?.userGender === 1 ? '男' : this.$store.getters?.userInfo
						?.userInfoDetail?.userGender === 0 ? '女' : '') : '',
					userStudentCard: this.$store.getters?.userInfo?.userInfoDetail?.userStudentCard || '',
				},
				rules: {
					'userPhoto': {
						type: 'string',
						required: true,
						message: '请上传头像',
						trigger: ['change']
					},
					'userName': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['change']
					},
					'userGender': {
						type: 'string',
						required: true,
						message: '请选择性别',
						trigger: ['change']
					},
					'userAddress': {
						type: 'string',
						required: true,
						message: '请输入用户地址',
						trigger: ['change']
					},
					'userCollege': {
						type: 'string',
						required: true,
						message: '请输入所在学院',
						trigger: ['change'],
					},
					'userEnterYear': {
						type: 'number',
						required: true,
						message: '请输入入学年份',
						trigger: ['change']
					},

					'userStudentCard': {
						type: 'string',
						required: true,
						message: '请上传学生证照片',
						trigger: ['change']
					},
				}
			}
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.userForm?.setRules(this.rules)
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					if (event.name === '1') {
						this.userInfoModel.userPhoto = result
						this.$refs.userForm.validateField('userPhoto')
					} else if (event.name === '2') {
						this.userInfoModel.userStudentCard = result
						this.$refs.userForm.validateField('userStudentCard')
					}
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))


					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${baseUrl}api/private/upload`, // 仅为示例，非真实的接口地址
						filePath: url,
						header: {
							"Authorization": (this.$store.getters.userInfo && this.$store.getters.userInfo
								?.token) ? this.$store.getters.userInfo?.token : ''
						},
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							const url = JSON.parse(res.data).data.url
							resolve(url)
						}
					});
				})
			},
			sexSelect(e) {
				this.userInfoModel.userGender = e.value
				this.userInfoModel.userGenderText = e.name
				this.$refs?.userForm.validateField('userGender')
				this.$refs?.userForm.validateField('userGenderText')
			},
			requireTimeClose() {
				this.showEnterYear = false
				this.$refs?.userForm.validateField('userEnterYear')
			},
			requireTimeConfirm(e) {
				this.showEnterYear = false
				this.userInfoModel.userEnterYear = uni.$u.timeFormat(e.value, 'yyyy')
				this.$refs?.userForm.validateField('userEnterYear')
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			submit() {
				this.userInfoModel.userPhone = this.$store.getters?.userInfo?.userPhone
				console.log(this.$store.getters.userInfo)
				console.log(this.userInfoModel)
				let pages = getCurrentPages(); // 当前页面
				let beforePage = pages[pages.length - 2];
				console.log(pages)
				this.$refs.userForm.validate().then(res => {
					const data = {
						"uid": this.$store.getters?.userInfo?.uid,
						"userName": this.userInfoModel.userName,
						"userPhoto": this.userInfoModel.userPhoto,
						"userGender": this.userInfoModel.userGender,
						"userPhone": this.userInfoModel.userPhone,
						"userCollege": this.userInfoModel.userCollege,
						"userEnterYear": this.userInfoModel.userEnterYear,
						"userAddress": this.userInfoModel.userAddress,
						"userStudentCard": this.userInfoModel.userStudentCard,
					}
					if (this.$store.getters.userInfo.userInfoDetail) { //有用户信息则是维护
						this.updateUserInfo(data)
					} else { //没有则是新用户
						this.createUserInfo(data)
					}


				}).catch(errors => {
					uni.$u.toast('请将用户信息填写完整！')
				})
			},

			createUserInfo(data) {
				this.$http('post', 'api/public/users/createUserInfo', {
					data,
					success: (res) => {
						const userInfo = this.$store.getters?.userInfo
						userInfo.userInfoDetail = {
							...userInfo.userInfoDetail,
							"uid": this.$store.getters?.userInfo?.uid,
							"userName": this.userInfoModel.userName,
							"userPhoto": this.userInfoModel.userPhoto,
							"userGender": this.userInfoModel.userGender,
							"userPhone": this.userInfoModel.userPhone,
							"userCollege": this.userInfoModel.userCollege,
							"userEnterYear": this.userInfoModel.userEnterYear,
							"userAddress": this.userInfoModel.userAddress,
							"userStudentCard": this.userInfoModel.userStudentCard,
						}
						console.log(userInfo)
						this.$store.dispatch('setLoginStste', userInfo)
						setTimeout(() => {
							let pages = getCurrentPages(); // 当前页面
							let beforePage = pages[pages.length - 2];

							uni.navigateBack({
								delta: 1,
								success: () => {
									beforePage?.$vm?.reload()
								}
							})
						}, 1000)
					},
					successMsg: '新增用户信息成功！'
				})
			},

			updateUserInfo(data) {
				this.$http('post', 'api/private/users/updateUserInfo', {
					data,
					success: (res) => {
						const userInfo = this.$store.getters.userInfo
						userInfo.userInfoDetail = {
							...userInfo.userInfoDetail,
							"uid": this.$store.getters.userInfo.uid,
							"userName": this.userInfoModel.userName,
							"userPhoto": this.userInfoModel.userPhoto,
							"userGender": this.userInfoModel.userGender,
							"userPhone": this.userInfoModel.userPhone,
							"userCollege": this.userInfoModel.userCollege,
							"userEnterYear": this.userInfoModel.userEnterYear,
							"userAddress": this.userInfoModel.userAddress,
							"userStudentCard": this.userInfoModel.userStudentCard,
						}
						console.log(userInfo)
						this.$store.dispatch('setLoginStste', userInfo)
						setTimeout(() => {
							let pages = getCurrentPages(); // 当前页面
							let beforePage = pages[pages.length - 2];

							uni.navigateBack({
								delta: 1,
								success: () => {
									beforePage?.$vm?.reload()
								}
							})
						}, 1000)
					},
					successMsg: '维护用户信息成功！'
				})
			},


		}
	}
</script>


<style scoped lang="scss">
	.form {
		height: 100vh;
		background: #fff;

	}

	.order-container {
		padding: 15px;

		.icon {
			width: 24px;
			height: 24px;
			margin-right: 10px;
		}

		.arrow {
			margin-left: 10px;
		}


	}





	.bottom {
		height: 90px;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		width: 100%;
		bottom: 10px;
		position: fixed;

		.operation {
			padding: 0 15px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: calc(100% - 30px);

		}

		.text {
			color: rgb(51, 51, 51);
			font-size: 14px;
		}

		.money {
			color: rgb(255, 104, 83);
			font-size: 14px;
		}

		.button {
			width: 100%
		}
	}

	.student-card {
		width: 300px;
		height: 150px;
		padding: 20px;
	}
</style>